package com.test.io.inputOutput;

import org.junit.Test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopyDemo {
    // 使用 fileInputStream fileOutPutStream 实现文件的复制
    @Test
    public void copy() {
        // 拷贝文件路径
        String copyFilePath = "d:\\newFile2.text";
        // 目标文件路径
        String targetFilePath = "f:\\newFile2.text";

        FileOutputStream ops = null;
        FileInputStream ips = null;
        try {
            ips = new FileInputStream(copyFilePath);
            ops = new FileOutputStream(targetFilePath);

            byte[] readBytes = new byte[9];
            int index = 0;
            while ((index = ips.read(readBytes)) != -1) {
                // ops.write(readBytes); 可能会造成数据重复写入的问题
                ops.write(readBytes, 0, index);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(ips != null) {
                    ips.close();
                }
                if(ops != null) {
                    ops.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
